package com.ntd.study.protocol.emq.core;

import ntd.util.UtilLog;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;


/**
 * mqtt 二次封装客户端
 *
 * @author liuwenju
 * @date 2021/07/20
 */
public class NtdMqttClient {

    private MqttClient mqttClient;

    public NtdMqttClient(NtdMqttConfig ntdMqttConfig) {
        this.mqttClient = init(ntdMqttConfig);
    }

    public void close() {
        try {
            mqttClient.disconnect();
            mqttClient.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void subscribe(String topic) {
        try {
            mqttClient.subscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息
     * @param msg
     * @throws MqttException
     */
    public void sendMessage(String topic, String msg) throws MqttException {
        sendMessage(topic, msg, 1);
    }

    /**
     * 发送消息
     * @param msg
     * @param qos
     * @throws MqttException
     */
    public void sendMessage(String topic, String msg, int qos) throws MqttException {
        // 消息发布所需参数
        MqttMessage message = new MqttMessage(msg.getBytes());
        message.setQos(qos);
        mqttClient.publish(topic, message);
    }

    private MqttClient init(NtdMqttConfig ntdMqttConfig) {
        try {
            if (!ntdMqttConfig.isInitTag()) {
                ntdMqttConfig.init();
            }

            MqttClient mqttClient = new MqttClient(ntdMqttConfig.getUrl(), ntdMqttConfig.getClientId(), ntdMqttConfig.getMqttClientPersistence());

            // 设置回调
            mqttClient.setCallback(ntdMqttConfig.getMqttCallback());

            // 建立连接
            mqttClient.connect(ntdMqttConfig.getMqttConnectOptions());

            UtilLog.info("连接成功:", ntdMqttConfig.getUrl(), ntdMqttConfig.getClientId());
            return mqttClient;
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return null;
    }

}
